package com.ny.dao.impl;

import com.ny.dao.StudentDao;
import com.ny.entity.Student;
import com.ny.until.SqlConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentDaoimpl implements StudentDao {
    Connection connection =  SqlConnection.getCon();

    public StudentDaoimpl() throws SQLException, ClassNotFoundException {
    }

    public int add(Student student) throws SQLException
    {
        String sql = "insert into students(name,phone,password) values(?,?,?)";

        PreparedStatement preparedStatement  = connection.prepareStatement(sql);

        preparedStatement.setString(1,student.getStudentName());
        preparedStatement.setString(2,student.getStudentPhone());
        preparedStatement.setString(3,student.getStudentPassword());
        return preparedStatement.executeUpdate();
    }

    @Override
    public Student login(String studentName, String studentPassword) throws SQLException {
        String sql = "select * from students where name = ? and password = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,studentName);
        preparedStatement.setString(2,studentPassword);
        ResultSet resultSet = preparedStatement.executeQuery();

        if (resultSet.next()){
            Student student = new Student();
            student.setStudentID(resultSet.getInt("student_id"));
            student.setStudentName(resultSet.getString("name"));
            student.setStudentPhone(resultSet.getString("phone"));
            student.setStudentPassword(resultSet.getString("password"));
            return student;
        }
        return null;
    }
}
